﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MusicWorks.Web.Logic.Views.Models;
using WebFormsMvp;
using MusicWorks.Web.Logic.Views;
using MusicWorks.Web.Logic.Helpers;
using MusicWorks.Web.Logic.ShoppingService.svc;

namespace MusicWorks.Web.Logic.Presenters
{
    public class BasketPresenter : Presenter<IBasketView>
    {
        IShoppingService _shopping;
        ISessionValueProvider _session;

        public BasketPresenter(IBasketView view)
            : this(view, ServiceBroker.CreateShoppingServiceInstance(), new CookieSessionValueProvider())
        {
        }

        public BasketPresenter(IBasketView view, IShoppingService shoppingService, ISessionValueProvider session)
            : base(view)
        {
            _shopping = shoppingService;
            _session = session;

            View.Load += View_Load;
        }

        void View_Load(object sender, EventArgs e)
        {
            var userId = _session.UserId;

            var basket = _shopping.GetBasket(userId, View.BasketName);
            BasketModel basketModel = null;

            if (basket == null)
            {
                basketModel = new BasketModel
                {
                    FormattedTotalPrice = string.Format("{0:C}", 0M),
                    LineItems = new LineItemModel[] { }
                };
            }
            else
            {
                basketModel = new BasketModel
                {
                    TotalPrice = basket.TotalPrice,
                    FormattedTotalPrice = string.Format("{0:C}", basket.TotalPrice)
                };
            }

            View.Model = basketModel;
        }

        public override void ReleaseView()
        {
            View.Load += View_Load;
        }
    }
}
